// pages/myCenter/liveRoom/index.js
import Common from '../../../common/common.js';
let common = new Common;

import moment from '../../../common/moment';


Page({

  /**
   * 页面的初始数据
   */
  data: {
    nowDate: '', //现在日期
    nowTime: "", //现在时间
    liveDate: '', //直播日期
    imgurl: '',
    showLiveModel: false,
    formData: {
      "name": "", //直播间名称
      "coverImg": "", //背景图
      "startTime": "",
      "endTime": "",
      "anchorName": "", //主播昵称
      "anchorWechat": "", //主播微信号
      "subAnchorWechat": "",
      "createrWechat": "",
      "shareImg": "", //分享图
      "feedsImg": "",
      "isFeedsPublic": 1, //是否开启官方收录 【1: 开启，0：关闭】，默认开启收录
      "type": 0, //直播间类型 【1: 推流，0：手机直播】
      "closeLike": 0,
      "closeGoods": 0,
      "closeComment": 0,
      "closeReplay": 0,
      "closeShare": 0,
      "closeKf": 1,
      "orgSeq": "",
      "storeName": ""
    }
  },
  onLoad: function (options) {
    this.setData({
      [`formData.anchorWechat`]: options.wxUsername,
      [`formData.orgSeq`]: getApp().globalData.shopInfo.orgSeq,
      [`formData.storeName`]: getApp().globalData.shopInfo.orgName,
      [`formData.name`]: getApp().globalData.shopInfo.orgName
    })

    this.setData({
      nowDate: moment().format('YYYY-MM-DD'),
      nowTime: moment().format('HH:mm'),
    })
    console.log(moment().format('YYYY-MM-DD'));
    console.log(moment().format('HH:mm'));
  },
  onReady: function () {

  },
  onShow: function () {},
  chooseDate(e) {
    this.setData({
      liveDate: e.detail.value
    })
  },
  //上传图片
  uploadImage(e) {
    let key = e.currentTarget.dataset.key;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFiles;
        console.log('tempFilePaths', tempFilePaths);

        wx.uploadFile({
          url: `${common.requestApi}/api/file-service/v1/zbHomeApi/uploadFileByWX?type=image`,
          filePath: tempFilePaths[0].path,
          header: {
            "token": wx.getStorageSync('token')
          },
          name: 'file',
          formData: {},
          success: res => {
            console.log(res);
            let respon = JSON.parse(res.data);
            if (respon.code) {
              this.setData({
                imgurl: respon.result.url,
                [`formData.coverImg`]: respon.result.mediaId,
                [`formData.shareImg`]: respon.result.mediaId,
                [`formData.feedsImg`]: respon.result.mediaId,
              })
            }
          },
          complete: com => {
            console.log(com)
          }
        })
      }
    })
  },
  getInputValue(e) {
    let key = e.currentTarget.dataset.key;
    this.setData({
      [`formData.${key}`]: e.detail.value.trim()
    })
  },
  changeTime(e) {
    let key = e.currentTarget.dataset.key;
    this.setData({
      [`formData.${key}`]: e.detail.value
    })
  },
  creatLiveRoom() {

    if (!this.data.formData.anchorName) {
      wx.showToast({
        title: '请填写主播昵称！',
        icon: 'none'
      })
      return false;
    }

    if (!this.data.liveDate) {
      wx.showToast({
        title: '请选择开播日期！',
        icon: 'none'
      })
      return false;
    }

    if (!this.data.formData.startTime) {
      wx.showToast({
        title: '请选择开播开始时间！',
        icon: 'none'
      })
      return false;
    }

    if (!this.data.formData.endTime) {
      wx.showToast({
        title: '请选择开播结束时间！',
        icon: 'none'
      })
      return false;
    }
    let data = JSON.parse(JSON.stringify(this.data.formData));
    data.startTime = this.data.liveDate + " " + this.data.formData.startTime;
    data.endTime = this.data.liveDate + " " + this.data.formData.endTime;


    const nowTime = new Date().getTime();
    const startTime = new Date(data.startTime.replace(/-/g, '/')).getTime();
    const endTime = new Date(data.endTime.replace(/-/g, '/')).getTime();

    if (nowTime >= startTime || startTime - nowTime <= 600000 || startTime >= endTime || endTime - startTime < 1800000) {
      //时间差小于半小时 
      wx.showToast({
        title: '开播时间必须为当前时间10分钟以后,且直播时间不得小于半小时！',
        icon: 'none'
      })
      return false;
    }


    data.startTime = data.startTime + ":00";
    data.endTime = data.endTime + ":00";
    console.log(data);

    wx.showModal({
      title: "提示",
      content: "是否开启直播？",
      success: res => {
        if (res.confirm) {
          common.requestAjax("/api/promotion-service/v1/zbHomePromotionApi/createHome", "POST", data).then(res => {
            if (res.data.code) {
              this.setData({
                showLiveModel: true
              })
            } else {
              wx.showToast({
                title: res.data.message,
                icon: "none"
              })
            }
          })
        }
      }
    })
  },
  hideLiveModal() {
    this.setData({
      showLiveModel: false
    })
  }
})